Submitting Forms

Course- AngularJS >

You can submit a form in two ways:

  • Using a button element with an ng-click attribute.
  • Using an ng-submit attribute (directive) on the form element.

In both cases a JavaScript function is called on the $scope object. You attach this JavaScript function to the $scope object in your controller function. The JavaScript function should send the data from the form to your server via AJAX.

Here is a form that uses the ng-click attribute on a button element:

<div ng-controller="MyController" >
  <form>
    <input type="text" id="name" ng-model="myForm.name" ng-minlength="5" ng-maxlength="12"> Name <br/>

    <select ng-model="myForm.car">
      <option value="nissan">Nissan</option>
      <option value="toyota">Toyota</option>
      <option value="fiat">Fiat</option>
    </select>

    <button ng-click="myForm.submitTheForm()">Submit Form</button>
  </form>

  <div>
    {{myForm.name}}
  </div>
  <div>
    {{myForm.car}}
  </div>
</div>

<script>
  angular.module("myapp", [])
     .controller("MyController", function($scope, $http) {
       $scope.myForm = {};
       $scope.myForm.name = "Jakob aitechtonic";
       $scope.myForm.car  = "nissan";

     $scope.myForm.submitTheForm = function(item, event) {
       console.log("--> Submitting form");
       var dataObject = {
          name : $scope.myForm.name
          ,car  : $scope.myForm.car
       };

       var responsePromise = $http.post("/angularjs-examples/json-test-data.jsp", dataObject, {});
       responsePromise.success(function(dataFromServer, status, headers, config) {
          console.log(dataFromServer.title);
       });
        responsePromise.error(function(data, status, headers, config) {
          alert("Submitting form failed!");
       });
     }

  });
</script>

Notice how the ng-click attribute points to the myForm.submitTheForm() function, and notice how the submitTheForm() function is attached to the $scope object inside the controller function.

Here is the same form using an ng-submit attribute to submit the form:

  <form ng-submit="myForm.submitTheForm()">
    <input type="text" id="name" ng-model="myForm.name" ng-minlength="5" ng-maxlength="12"> Name <br/>

    <select ng-model="myForm.car">
      <option value="nissan">Nissan</option>
      <option value="toyota">Toyota</option>
      <option value="fiat">Fiat</option>
    </select>

    <input type="submit" value="Submit Form">

  </form>

As you can see, the two mechanisms are very similar. They both call a submit function on the $scope object.